<!-- 填空题库 -->
<template>
    <div>
        <!-- 第一部分 -->
        <el-row class="Header">
            <el-col :span="12">
                <div>
                    <el-input placeholder="请输入题目编号 F-xxx" v-model="param.questionNumber" clearable>
                        <el-select v-model="param.chapter" slot="prepend" placeholder="请选择">
                            <el-option v-for="(item,index) in chapters" :key="index"
                                :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                        </el-select>
                        <el-button slot="append" icon="el-icon-search"></el-button>
                    </el-input>
                </div>
            </el-col>

            <el-col :span="12">
                <div class="addChooseButton">
                    <el-button type="primary" @click="fillEmptyFold=true">添加程序阅读题</el-button>
                </div>
            </el-col>
        </el-row>

        <!-- 添加题目的对话框 -->
        <el-dialog title="添加程序阅读题" :visible.sync="fillEmptyFold" width="50%" :before-close="handleClose">
            <!-- form 表单 -->
            <el-form :model="addFillEmptyparam" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号" prop="questionNumber">
                    <el-input placeholder="请输入题目编号 F-xxx" v-model="addFillEmptyparam.questionNumber"></el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapter">
                    <el-select v-model="addFillEmptyparam.chapter" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input type="textarea" autosize maxlength="255" placeholder="请输入题目描述"
                        v-model="addFillEmptyparam.description"></el-input>
                </el-form-item>
                <!-- 题目代码片段 -->
                <el-form-item label="代码片段" prop="code">
                    <el-input type="textarea" :autosize="{ minRows: 2}" placeholder="请输入代码片段"
                        v-model="addFillEmptyparam.code"></el-input>
                </el-form-item>
                <!-- 答案注册 -->
                <el-form-item label="答案录入">
                    <div v-for="(item, index) in addFillEmptyparam.answers" :key="index" class="addAnswer">
                        <!-- 将index赋值给order，将输入值赋值给answer。 -->
                        <el-input v-model="item.answer">
                            <template slot="prepend">答案{{index+1}}</template>
                        </el-input>
                        <el-button @click.prevent="removeAnswer(item)">删除</el-button>
                    </div>
                    <el-button @click="addDomain">新增答案</el-button>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="addQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 第二部分 -->
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100"></el-table-column>
            <el-table-column label="章节" prop="chapter" width="100"></el-table-column>
            <el-table-column label="题目编号" prop="questionNumber" width="100"></el-table-column>
            <el-table-column label="题目描述" prop="description"></el-table-column>
            <!-- 折叠的选项区域   区域显示这个题的代码片段和题目答案 -->
            <el-table-column label="题目具体" type="expand" width="100">
                <template slot-scope="props">
                    <!-- 代码片段的展示 -->
                    <el-form label-position="left" inline class="fold_part">
                        <el-form-item>
                            <pre><code>{{ props.row.code }}</code></pre>
                        </el-form-item>
                    </el-form>
                    <!-- 答案的展示 -->
                    <el-form label-position="left" inline class="fold_part"
                        v-for="(item,index) in tableData[props.$index].answers" :key="index">
                        <el-form-item>
                            <span>第{{index + 1}}个答案是：{{ item.answer }}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
                <template slot-scope="scoped">
                    <el-button type="primary" icon="el-icon-edit" @click="editfillEmpty(scoped.row.id)"
                        circle></el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="deleteFillEmpty(scoped.row.id)"
                        circle></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 删除题目的提示框 -->
        <el-dialog title="提示框" :visible.sync="deletefillEmptyFold" width="30%" :before-close="deletehandleClose">
            <span>确定删除吗</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deletehandleClose">取 消</el-button>
                <el-button type="primary" @click="deleteToFillEmpty">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改题目的对话框 -->
        <el-dialog title="修改程序阅读题" :visible.sync="editfillEmptyFold" width="50%" :before-close="edithandleClose">
            <!-- form 表单 -->
            <el-form :model="editFillEmptyparam" :rules="rules" ref="editruleForm" label-width="100px"
                class="demo-ruleForm">
                <!-- 题目编号 -->
                <el-form-item label="题目编号">
                    <el-input :disabled="true" placeholder="请输入题目编号 F-xxx"
                        v-model="editFillEmptyparam.questionNumber"></el-input>
                </el-form-item>
                <!-- 章节选择 -->
                <el-form-item label="章节选择" prop="chapter">
                    <el-select disabled v-model="editFillEmptyparam.chapter" placeholder="请选择章节">
                        <el-option v-for="(item,index) in chapters" :key="index"
                            :label="item.chapterNumber+item.description" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 题目描述 -->
                <el-form-item label="题目描述" prop="description">
                    <el-input type="textarea" autosize maxlength="255" placeholder="请输入题目描述"
                        v-model="editFillEmptyparam.description"></el-input>
                </el-form-item>
                <!-- 题目代码片段 -->
                <el-form-item label="代码片段" prop="code">
                    <el-input type="textarea" :autosize="{ minRows: 2}" placeholder="请输入代码片段"
                        v-model="editFillEmptyparam.code"></el-input>
                </el-form-item>
                <!-- 答案注册 -->
                <el-form-item label="答案录入">
                    <div v-for="(item, index) in editFillEmptyparam.answers" :key="index" class="addAnswer">
                        <!-- 将index赋值给order，将输入值赋值给answer。 -->
                        <el-input v-model="item.answer">
                            <template slot="prepend">答案{{index+1}}</template>
                        </el-input>
                        <el-button @click.prevent="editremoveAnswer(item)">删除</el-button>
                    </div>
                    <el-button @click="editAddDomain">新增答案</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editruleForm">重置</el-button>
                <el-button type="primary" @click="editQuestion">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 第三部分 -->
        <!-- 分页查询 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="param.currentPage" :page-sizes="[5, 8, 10]" :page-size="param.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

    </div>


</template>


<script>
    export default {
        watch: {
            'param.chapter': { // 监视params对象中的 chapter 章节id 属性变化  
                handler(newVal) {
                    this.param.questionNumber = ""
                    // 因为  params.chapter 发生变化 这里就会自动发送一次请求
                    this.getFillEmptyQuestionlist()
                },
            },
            'param.questionNumber': { // 监视param对象中的 questionNumber 属性是否为空 
                handler(newVal) {
                    if (newVal === null || newVal === "") {
                        this.getFillEmptyQuestionlist()
                    }
                },
            },
        },
        created() {
            this.getChapter()
            this.getFillEmptyQuestionlist()
        },
        data() {
            // 判断编码是否重复
            var cf = (value) => {
                for (let i = 0; i < this.tableData.length; i++) {
                    if (value === this.tableData[i].questionNumber) {
                        return true
                    }
                }
                return false
            }
            // 编号表单验证
            var questionNumberRule = (rule, value, callback) => {
                var regex = /^F-[A-F0-9][0-9]{2,}$/;
                if (!value) {
                    return callback(new Error('请输入编号'));
                } else if (!regex.test(value)) {
                    return callback(new Error('编码格式不满足'));
                } else if (cf(value)) {
                    callback(new Error('编码已经存在'));
                } else {
                    callback();
                }
            };
            return {
                // 章节信息
                chapters: [],
                // 分页查询请求参数
                param: {
                    questionNumber: "",      // 搜索框内容，表示题目编号
                    chapter: 1,             // 章节id
                    currentPage: 1,         // 页数
                    pageSize: 5             // 每页记录数
                },
                // 表格数据
                tableData: [],
                total: null,
                // 添加程序阅读题的参数
                addFillEmptyparam: {
                    questionNumber: "",
                    chapter: "",
                    description: "",
                    code: "",
                    answers: [
                        { order: 1, answer: "" }
                    ]
                },
                // 修改程序阅读题的参数
                editFillEmptyparam: {
                    id: null,
                    questionNumber: "",
                    chapter: "",
                    description: "",
                    code: "",
                    answers: []
                },
                // 备用答案
                spareAnswers: [],
                // 表单验证
                rules: {
                    questionNumber: [
                        { validator: questionNumberRule, trigger: 'blur' }
                    ],
                    description: [
                        { required: true, message: '请输入题目描述', trigger: 'blur' },
                    ],
                    answer: [
                        { required: true, message: '答案不能为空', trigger: 'blur' },
                    ],
                    chapter: [
                        { required: true, message: '请选择章节', trigger: 'blur' },
                    ],
                    code: [
                        { required: true, message: '请输入代码', trigger: 'blur' },
                    ]
                },
                // 控制添加题目的对话框的开关
                fillEmptyFold: false,
                // 控制修改题目的对话框的开关
                editfillEmptyFold: false,
                // 控制删除题目的提示框
                deletefillEmptyFold:false,
                // 需要删除的题目id
                deleteFillEmptyId: null
            };
        },
        methods: {
            // 获取章节信息
            async getChapter() {
                const { data: res } = await this.$axios.get("/chapter/getChapter")
                this.chapters = res.data
            },
            // 分页查询，发送请求
            async getFillEmptyQuestionlist() {
                const { data: res } = await this.$axios.post("/FillEmpty/getFillEmptyQuestion", this.param)
                this.tableData = res.data.records
                this.total = res.data.total
            },



            // 分页查询数据发生变化
            handleSizeChange(newPageSize) {
                this.param.pageSize = newPageSize
                this.getFillEmptyQuestionlist()
            },
            handleCurrentChange(newCurrent) {
                this.param.currentPage = newCurrent
                this.getFillEmptyQuestionlist()
            },
            // 添加题目对话框关闭前的操作
            handleClose() {
                this.resetForm()
                this.fillEmptyFold = false
            },
            // 重置添加题目
            resetForm() {
                this.$refs.ruleForm.resetFields();
                this.addFillEmptyparam.answers = [{ order: 1, answer: "" }]
            },

            // 给addFillEmptyparam的answers的order排序
            answerOrder() {
                for (let i = 0; i < this.addFillEmptyparam.answers.length; i++) {
                    this.addFillEmptyparam.answers[i].order = i + 1
                }
            },
            // 新增试题的答案区域。新增答案
            addDomain() {
                this.addFillEmptyparam.answers.push({
                    order: null, answer: ""
                });
                this.answerOrder()
            },
            // 新增答案的删除答案
            removeAnswer(item) {
                var index = this.addFillEmptyparam.answers.indexOf(item)
                var length = this.addFillEmptyparam.answers.length
                if (length === 1) {
                    return this.$message("想干啥，不想设置答案了哈")
                }
                if (index !== -1) {
                    this.addFillEmptyparam.answers.splice(index, 1)
                }
                this.answerOrder()
            },
            // 判断答案是否为空
            AnswerIsEmpty() {
                for (var i = 0; i < this.addFillEmptyparam.answers.length; i++) {
                    if (this.addFillEmptyparam.answers[i].answer === null ||
                        this.addFillEmptyparam.answers[i].answer === "") {
                        return true
                    }
                }
                return false
            },
            // 添加题目
            addQuestion() {
                this.$refs.ruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    if (this.AnswerIsEmpty()) {
                        return this.$message.error("请完善答案")
                    }
                    const { data: res } = await this.$axios.post('/FillEmpty/addQuestion', this.addFillEmptyparam)
                    if (res.code === 200) {
                        this.getFillEmptyQuestionlist()
                        this.handleClose()
                        return this.$message.success("添加成功")
                    } else if (res.code === 511) {
                        return this.$message.error("编码重复")
                    } else {
                        return this.$message.error("你输入的信息有误")
                    }
                })
            },

            // 修改题目的方法
            // 1. 打开输入框，传入一个id值。将editFillEmptyparam赋值
            editfillEmpty(id) {
                var FillEmpty = this.tableData.find((item) => item.id === id)
                this.editFillEmptyparam.questionNumber = FillEmpty.questionNumber
                this.editFillEmptyparam.chapter = FillEmpty.chapter
                this.editFillEmptyparam.description = FillEmpty.description
                this.editFillEmptyparam.code = FillEmpty.code
                for (let i = 0; i < FillEmpty.answers.length; i++) {
                    this.editFillEmptyparam.answers.push({
                        order: FillEmpty.answers[i].order,
                        answer: FillEmpty.answers[i].answer,
                        id: FillEmpty.answers[i].id,
                    })
                    this.spareAnswers.push({
                        order: FillEmpty.answers[i].order,
                        answer: FillEmpty.answers[i].answer,
                        id: FillEmpty.answers[i].id,
                    })
                }
                this.editFillEmptyparam.id = FillEmpty.id
                this.editfillEmptyFold = true
            },
            // 2. 重置对话框的内容
            editruleForm() {
                this.$refs.editruleForm.resetFields();
                this.editFillEmptyparam.answers = this.spareAnswers
            },
            // 3. 添加题目对话框关闭前的操作
            edithandleClose() {
                this.editruleForm()
                this.editFillEmptyparam.answers = []
                this.editfillEmptyFold = false
            },
            // 给editFillEmptyparam的answers的order排序
            editanswerOrder() {
                for (let i = 0; i < this.editFillEmptyparam.answers.length; i++) {
                    this.editFillEmptyparam.answers[i].order = i + 1
                }
            },
            // 4. 修改题目的新增答案
            editAddDomain() {
                this.editFillEmptyparam.answers.push({
                    order: null, answer: "", id: null
                });
                this.editanswerOrder()
            },
            // 5. 修改题目的删除答案
            editremoveAnswer(item) {
                var index = this.editFillEmptyparam.answers.indexOf(item)
                var length = this.editFillEmptyparam.answers.length
                if (length === 1) {
                    return this.$message("想干啥，不想设置答案了哈")
                }
                if (index !== -1) {
                    this.editFillEmptyparam.answers.splice(index, 1)
                }
                this.editanswerOrder()
            },
            // 判断答案是否为空
            editAnswerIsEmpty() {
                for (var i = 0; i < this.editFillEmptyparam.answers.length; i++) {
                    if (this.editFillEmptyparam.answers[i].answer === null ||
                        this.editFillEmptyparam.answers[i].answer === "") {
                        return true
                    }
                }
                return false
            },
            // 修改题目
            editQuestion() {
                this.$refs.editruleForm.validate(async valid => {
                    if (!valid) return this.$message.error("请完善表格")
                    if (this.editAnswerIsEmpty()) {
                        return this.$message.error("请完善答案")
                    }
                    const { data: res } = await this.$axios.post('/FillEmpty/updateQuestion', this.editFillEmptyparam)
                    if (res.code === 200) {
                        this.getFillEmptyQuestionlist()
                        this.edithandleClose()
                        return this.$message.success("添加成功")
                    } else if (res.code === 512) {
                        return this.$message.error("试题关联了试卷，不能修改答案")
                    }
                    else {
                        return this.$message.error("你输入的信息有误")
                    }
                })
            },

            // 删除题目
            deleteFillEmpty(id) {
                this.deleteFillEmptyId = id
                this.deletefillEmptyFold = true
            },
            // 提示框关闭前的操作
            deletehandleClose(){
                this.deleteFillEmptyId=null
                this.deletefillEmptyFold=false
            },
            // 删除题目
            async deleteToFillEmpty(){
                const { data: res } = await this.$axios.delete("/FillEmpty/deleteFillEmpty",{
                    params:{
                        id:this.deleteFillEmptyId
                    }
                })
                if(res.code===200){
                    this.getFillEmptyQuestionlist()
                    this.$message.success("删除成功")
                }else if(res.code===512){
                    this.$message.error("该试题关联了试卷，不能删除")
                }
                else{
                    this.$message.error("删除失败")
                }
                return this.deletehandleClose()
            }
        }
    }
</script>

<style lang="less" scoped>
    /* 头部样式 */
    .Header {
        margin-bottom: 15px;

        /* 选择框 */
        .el-select {
            width: 300px;
        }

        /* 添加题目按钮 */
        .addChooseButton {
            text-align: right;

            .el-button {
                margin-right: 50px;
            }
        }
    }

    /* 第二部分 */
    /* 表格的折叠部分 */
    .fold_part {

        /* background-color: #659bbe; */
        .el-form-item {
            /* background-color: #429c18; */
            margin: 0;
            padding: 0;

            pre {
                margin-right: 20px;
                white-space: pre-wrap;
                background-color: #f2f2f2;
                margin-left: 30px;
                font-size: 16px;
                line-height: 16px;
                margin-bottom: 0;
                padding-bottom: 10px;
            }

            span {
                margin: 0;
                padding: auto;
            }
        }
    }

    /* 添加题目答案录入区域 */
    .addAnswer {
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
    }
</style>